<template>
  <div class="p-4">
    <div class="mb-3">
      <form-search
        :formFields="formFields"
        @search="handleQuery"
        @reset="handleQuery"
      />
    </div>
    <a-row :gutter="10" class="mb-2">
      <a-col v-has-permi="['system:role:add']">
        <a-button color="success" @click="handleAdd">
          {{ t("common.add") }}
        </a-button>
      </a-col>
      <a-col v-has-permi="['system:role:delete']">
        <a-popconfirm
          :title="t('common.confirmDelete')"
          :ok-text="t('common.okText')"
          :cancel-text="t('common.cancelText')"
          @confirm="confirm"
          @cancel="cancel"
        >
          <a-button :disabled="!hasSelected" color="error">
            {{ t("common.delete") }}
          </a-button>
        </a-popconfirm>
      </a-col>
    </a-row>

    <a-table
      :loading="loading"
      rowKey="id"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="roleList"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #roleKey="{ record }">
        <router-link :to="'dictData/' + record.id">
          <span class="text-[#1890ff]">{{ record.roleKey }}</span>
        </router-link>
      </template>
      <template #status="{ record }">
        <span>{{ selectDictLabel(statusOptions, record.status) }}</span>
      </template>
      <template #action="{ record }">
        <span>
          <a-button
            type="link"
            color="success"
            class="mr-3"
            @click="handleUpdate(record)"
            v-has-permi="['system:role:update']"
          >
            {{ t("common.update") }}
          </a-button>
          <a-button
            type="link"
            color="warning"
            class="mr-3"
            @click="handleScopeOpen(record)"
            v-has-permi="['system:role:update']"
          >
            {{ t("routes.role.dataAuth") }}
          </a-button>
          <a-popconfirm
            :title="t('common.confirmDelete')"
            :ok-text="t('common.okText')"
            :cancel-text="t('common.cancelText')"
            @confirm="confirm(record)"
            @cancel="cancel"
          >
            <a-button
              type="link"
              color="error"
              v-has-permi="['system:role:delete']"
            >
              {{ t("common.delete") }}
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </a-table>

    <!-- 新增修改推窗 -->
    <AddOrUpdate @finished="handleFinished" ref="addOrUpdateRef" />

    <!-- 数据权限推窗 -->
    <UpdateDataAuthority
      @finished="handleAuthFinished"
      ref="updateDataAuthorityRef"
    />
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  onMounted,
  toRefs,
  computed,
} from "vue";
import { Row, Col, Popconfirm, Table } from "ant-design-vue";
import { getRole, delRole } from "@/api/admin/system/role";
import { getDict, selectDictLabel } from "@/utils/dictFormat";
import { useAppStore } from "@/store/modules/app";
import { message as Message } from "ant-design-vue";
import { TableState } from "ant-design-vue/es/table/interface";

import FormSearch from "@/components/FormSearch/index.vue";

import { IRole } from "@/api/admin/system/role/type";
import { IData } from "@/api/admin/system/dict/data/type";
import { useI18n } from "@/hooks/useI18n";
import AddOrUpdate from "./AddOrUpdate.vue";
import UpdateDataAuthority from "./UpdateDataAuthority.vue";

const { t } = useI18n();

type Pagination = TableState["pagination"];

const columns = [
  {
    title: t("routes.role.roleName"),
    dataIndex: "roleName",
    key: "roleName",
    align: "center",
  },
  {
    title: t("routes.role.roleKey"),
    dataIndex: "roleKey",
    key: "roleKey",
    align: "center",
  },
  {
    title: t("routes.role.roleSort"),
    dataIndex: "roleSort",
    key: "roleSort",
    align: "center",
  },
  {
    title: t("routes.role.status"),
    dataIndex: "status",
    key: "status",
    align: "center",
    slots: { customRender: "status" },
  },
  {
    title: t("routes.role.createdBy"),
    dataIndex: "createdBy",
    key: "createdBy",
    align: "center",
  },
  {
    title: t("routes.role.createdAt"),
    dataIndex: "createdAt",
    key: "createdAt",
    align: "center",
  },
  {
    title: t("routes.role.action"),
    key: "action",
    align: "center",
    slots: { customRender: "action" },
  },
];

export default defineComponent({
  name: "Role",
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-popconfirm": Popconfirm,
    "a-table": Table,
    FormSearch,
    AddOrUpdate,
    UpdateDataAuthority,
  },
  setup() {
    const loading = computed(() => useAppStore().loading);
    const statusOptions = ref<IData[]>([]);

    // 查询表单操作
    const queryParams = reactive({
      pageNum: 1,
      pageSize: 10,
      roleName: undefined || "",
      status: undefined || "",
    });
    const formFields = reactive([
      {
        type: "input",
        label: t("routes.role.roleName"),
        name: "roleName",
        value: "",
        placeholder: t("routes.role.roleNamePlaceholder"),
      },
      {
        type: "select",
        label: t("routes.role.status"),
        name: "status",
        value: undefined,
        placeholder: t("routes.role.statusPlaceholder"),
        normalizer: {
          value: "dictValue",
          label: "dictLabel",
        },
        options: statusOptions,
      },
    ]);
    const handleQuery = (query: { roleName: string; status: string }) => {
      pagination.value.current = 1;
      queryParams.pageNum = pagination.value.current;
      queryParams.roleName = query.roleName;
      queryParams.status = query.status;
      getList(queryParams);
    };
    // 表格操作
    const roleList = ref<IRole[]>([]);
    const pagination = ref({
      total: 0,
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`,
    });

    const handleTableChange = (page: Pagination) => {
      (pagination.value as Pagination) = page;
      queryParams.pageNum = pagination.value.current;
      queryParams.pageSize = pagination.value.pageSize;
      getList(queryParams);
    };
    const state = reactive({
      selectedRowKeys: [],
    });
    const hasSelected = computed(() => state.selectedRowKeys.length > 0);

    const onSelectChange = (selectedRowKeys) => {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      state.selectedRowKeys = selectedRowKeys;
    };

    const getList = (queryParams?: {}) => {
      getRole(queryParams).then((res) => {
        console.log(res);
        roleList.value = res.data.rows;
        pagination.value.total = res.data.count;
        state.selectedRowKeys = [];
        roleList.value.forEach((list) => {
          if (list.status === "1") {
            list.checked = true;
          } else {
            list.checked = false;
          }
        });
      });
    };

    // 完成表单提交回调
    const handleFinished = () => {
      getList(queryParams);
    };
    const addOrUpdateRef = ref();
    // 新增按钮操作
    const handleAdd = () => {
      addOrUpdateRef.value.handleShow();
    };
    // 更新按钮操作
    const handleUpdate = (row) => {
      addOrUpdateRef.value.handleShow(row);
    };
    // 确认删除
    const confirm = (row) => {
      const ids = row.id || state.selectedRowKeys;
      delRole(ids).then(() => {
        if (
          (ids.length && ids.length === roleList.value.length) ||
          roleList.value.length === 1
        ) {
          if (
            Math.ceil(pagination.value.total / queryParams.pageSize) ===
              queryParams.pageNum &&
            queryParams.pageNum > 1
          ) {
            queryParams.pageNum--;
          }
        }
        getList(queryParams);
        Message.success(t("common.deleteSuccess"));
      });
    };
    // 取消删除
    const cancel = (e: MouseEvent) => {
      console.log(e);
      Message.success(t("common.cancelDelete"));
    };

    const updateDataAuthorityRef = ref();
    // 完成数据权限表单提交回调
    const handleAuthFinished = () => {
      getList(queryParams);
    };
    // 显示
    const handleScopeOpen = (row) => {
      updateDataAuthorityRef.value.handleShow(row);
    };

    const init = () => {
      getList(queryParams);
    };

    onMounted(async () => {
      statusOptions.value = await getDict("sys_normal_disable");
      init();
    });

    return {
      t,
      loading,
      formFields,
      handleQuery,
      roleList,
      columns,
      pagination,
      handleTableChange,
      selectDictLabel,
      statusOptions,
      ...toRefs(state),
      hasSelected,
      onSelectChange,

      confirm,
      cancel,
      handleAdd,
      handleUpdate,
      addOrUpdateRef,
      handleFinished,

      handleScopeOpen,
      updateDataAuthorityRef,
      handleAuthFinished,
    };
  },
});
</script>
